#include "image.h"

/**
   Allocates memory for dgrayimage
 */
DGrayImage* CreateDGrayImage(int nx, int ny)
{
   int i;
   DGrayImage* img;
   img = (DGrayImage*)malloc(sizeof(DGrayImage));
   img->nx = nx;
   img->ny = ny;
   img->val = (Vector**)malloc(sizeof(Vector*)*nx);
   for (i = 0; i < nx; i++)
      img->val[i] = (Vector*)malloc(sizeof(Vector)*ny);
   
   return img;
}

/**
   Destroys double valued gray image
 */
void DestroyDGrayImage(DGrayImage *img)
{
   int i;

   if (img)
   {
      for (i = 0; i < img->nx; i++)
         free(img->val[i]);

      free(img->val);
      free(img);
   }
}

/**
   Translates its quadrants
 */
void TransposeGrayImage(GrayImage *img)
{
   int i, j;
   int val;
   int nx2, ny2;
   int* v;

   nx2 = img->nx/2;
   ny2 = img->ny/2;

   // switch the first with the forth
   for (i = 0; i < nx2; i++)
   {
      for (j = 0; j < ny2; j++)
      {
         val = img->val[j][i];
         v = &(img->val[j + ny2][i + nx2]);
         img->val[j][i] = *v;
         *v = val;
      }
   }

   // switch the second with the third
   for (i = nx2; i < img->nx; i++)
   {
      for (j = 0; j < ny2; j++)
      {
         val = img->val[j][i];
         v = &(img->val[j + ny2][i - nx2]);
         img->val[j][i] = *v;
         *v = val;
      }
   }
}

/**
   Convert a dgray image to a gray image using
   pixel magnitude and normalizing it with log
 */
GrayImage* ConvertToGrayImage(DGrayImage* img)
{
   int i, j;
   GrayImage* gimg;

   gimg = CreateGrayImage(img->nx, img->ny);   

   for (i = 0; i < img->nx; i++)
      for (j = 0; j < img->ny; j++)
         gimg->val[j][i] = 
            (int)(255.0 * log(1.0 + 
                     sqrt(img->val[j][i].real * img->val[j][i].real +
                          img->val[j][i].img * img->val[j][i].img)));

   return gimg;
}
